package org.ycx.upms.web.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.common.validator.NotNullValidator;
import org.ycx.common.validator.ValidationErrorToString;
import org.ycx.upms.common.constants.SecurityConstants;
import org.ycx.upms.dao.model.SecSystem;
import org.ycx.upms.dao.model.SecSystemExample;
import org.ycx.upms.service.ISecSystemService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* SecSystemcontroller
* Created by yang on 2017-07-19 16:25:40.
*/
@Controller
@RequestMapping("/sec/system")
public class SecSystemController{

    private static Logger _log = LoggerFactory.getLogger(SecSystemController.class);

    private static final String PRE="sec/system/";

    @Autowired
    private ISecSystemService service;

    /**
    * 首页
    *
    * @param modelMap
    * @return
    */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
    return PRE+"index";
    }

    /**
    * 新增页面
    *
    * @param modelMap
    * @return
    */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap) {
    return PRE+"create";
    }

    /**
    * 更新页面
    *
    * @param id
    * @param modelMap
    * @return
    */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        SecSystem bean = this.service.selectByPrimaryKey(id);
        modelMap.put("bean",bean);
        return PRE+"update";
    }
    /**
    * 更新页面
    *
    * @param id
    * @param modelMap
    * @return
    */
    @RequestMapping("/detail/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
        SecSystem bean = this.service.selectByPrimaryKey(id);
        modelMap.put("bean",bean);
        return PRE+"detail";
    }

    /**
    * 新增功能
    *
    * @param bean
    * @param session
    * @return
    */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(SecSystem bean, HttpSession session) {
    ComplexResult result = FluentValidator.checkAll()
                                .on(bean.getName (),new NotNullValidator("系统名称"))
                            .on(bean.getSystemDesc (),new NotNullValidator("系统描述"))
                            .on(bean.getIcon (),new NotNullValidator("系统图标"))
                            .on(bean.getTheme (),new NotNullValidator("系统主题"))
                            .on(bean.getBaseuri (),new NotNullValidator("域名"))
                            .on(bean.getState (),new NotNullValidator("状态"))
                            .on(bean.getSysKey (),new NotNullValidator("KEY"))
                            .on(bean.getBanner (),new NotNullValidator("banner"))
                                                                    .doValidate()
        .result(ResultCollectors.toComplex());
        if(!result.isSuccess()){
            RespMSG error = new RespMSG(RespCode.FAIL);
            error.setDesc(ValidationErrorToString.errorToString(result.getErrors(),"\n\r"));
        return error;
        }
        bean.setCreateTs(new Date());
        bean.setUpdateTs(new Date());
        bean.setCreateUid((Integer) session.getAttribute(SecurityConstants.CURRENT_UID));
        bean.setUpdateUid((Integer) session.getAttribute(SecurityConstants.CURRENT_UID));
        int count = service.insertSelective(bean);
        return new RespMSG(RespCode.SUCCESS);
    }
    /**
    * 更新功能
    *
    * @param id
    * @param bean
    * @return
    */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, SecSystem bean, HttpSession session) {
    //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll()
                                                    .on(bean.getName (),new NotNullValidator("系统名称"))
                                            .on(bean.getSystemDesc (),new NotNullValidator("系统描述"))
                                            .on(bean.getIcon (),new NotNullValidator("系统图标"))
                                            .on(bean.getTheme (),new NotNullValidator("系统主题"))
                                            .on(bean.getBaseuri (),new NotNullValidator("域名"))
                                            .on(bean.getState (),new NotNullValidator("状态"))
                                            .on(bean.getSysKey (),new NotNullValidator("KEY"))
                                            .on(bean.getBanner (),new NotNullValidator("banner"))
                                                                                                                .doValidate()
            .result(ResultCollectors.toComplex());
        if(!result.isSuccess()){
            RespMSG error = new RespMSG(RespCode.FAIL);
            error.setDesc(ValidationErrorToString.errorToString(result.getErrors(),"\n\r"));
            return error;
        }
        bean.setUpdateTs(new Date());
        bean.setUpdateUid((Integer) session.getAttribute(SecurityConstants.CURRENT_UID));
        int count = service.updateByPrimaryKeySelective(bean);
        return new RespMSG(RespCode.SUCCESS);
    }

    /**
    * 删除
    *
    * @param ids
    * @return
    */
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public RespMSG delete(@PathVariable("ids") String ids) {
        int count = service.deleteByPrimaryKeys(ids);
        return new RespMSG(RespCode.SUCCESS);
    }


    @RequestMapping("/list")
    @ResponseBody
    public Object list(
    @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
    @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
    @RequestParam(required = false, defaultValue = "", value = "search") String search,
    @RequestParam(required = false, value = "sort") String sort,
    @RequestParam(required = false, value = "order") String order) {
        SecSystemExample beanExample = new SecSystemExample();
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
        beanExample.setOrderByClause(sort + " " + order);
        }
        //TODO 模糊查询定义
        List<SecSystem> rows = service.selectByExampleForOffsetPage(beanExample, offset, limit);
        long total = service.countByExample(beanExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }
}
